import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { ChatRoom, Message, User, SendMessageRequest, CreateChatRoomRequest } from '@/types'
import { apiService } from '@/services/api'
import { signalRService } from '@/services/signalr'

export const useChatStore = defineStore('chat', () => {
  // 状态
  const chatRooms = ref<ChatRoom[]>([])
  const currentChatRoom = ref<ChatRoom | null>(null)
  const messages = ref<Message[]>([])
  const typingUsers = ref<Map<number, Set<number>>>(new Map()) // chatRoomId -> Set<userId>
  const onlineUsers = ref<Set<number>>(new Set())
  const isLoading = ref(false)
  const error = ref<string | null>(null)

  // 计算属性
  const sortedChatRooms = computed(() => {
    return [...chatRooms.value].sort((a, b) => {
      const aTime = a.lastMessage?.createdAt || a.createdAt
      const bTime = b.lastMessage?.createdAt || b.createdAt
      return new Date(bTime).getTime() - new Date(aTime).getTime()
    })
  })

  const currentChatMessages = computed(() => {
    if (!currentChatRoom.value) return []
    return messages.value
      .filter(msg => msg.chatRoomId === currentChatRoom.value!.id)
      .sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime())
  })

  const currentTypingUsers = computed(() => {
    if (!currentChatRoom.value) return []
    const typingSet = typingUsers.value.get(currentChatRoom.value.id)
    return typingSet ? Array.from(typingSet) : []
  })

  // 初始化 SignalR 事件监听
  const initializeSignalRListeners = () => {
    // 接收消息
    signalRService.onReceiveMessage((message: Message) => {
      addMessage(message)
      updateChatRoomLastMessage(message)
    })

    // 用户上线/下线
    signalRService.onUserOnline((userId: number) => {
      onlineUsers.value.add(userId)
      updateUserOnlineStatus(userId, true)
    })

    signalRService.onUserOffline((userId: number) => {
      onlineUsers.value.delete(userId)
      updateUserOnlineStatus(userId, false)
    })

    // 用户开始/停止输入
    signalRService.onUserStartedTyping((chatRoomId: number, userId: number) => {
      addTypingUser(chatRoomId, userId)
    })

    signalRService.onUserStoppedTyping((chatRoomId: number, userId: number) => {
      removeTypingUser(chatRoomId, userId)
    })

    // 消息编辑/删除
    signalRService.onMessageEdited((message: Message) => {
      updateMessage(message)
    })

    signalRService.onMessageDeleted((messageId: number) => {
      removeMessage(messageId)
    })

    // 错误处理
    signalRService.onError((errorMessage: string) => {
      error.value = errorMessage
    })

    // 标记已读确认
    signalRService.onMarkedAsRead((chatRoomId: number) => {
      const room = chatRooms.value.find(r => r.id === chatRoomId)
      if (room) {
        room.unreadCount = 0
        console.log(`收到服务器确认：聊天室 ${chatRoomId} 已标记为已读`)
      }
    })
  }

  // 获取用户聊天室列表
  const fetchChatRooms = async () => {
    isLoading.value = true
    try {
      const rooms = await apiService.getUserChatRooms()
      chatRooms.value = rooms
    } catch (err: any) {
      error.value = err.response?.data?.message || '获取聊天室列表失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }

  // 创建聊天室
  const createChatRoom = async (roomData: CreateChatRoomRequest) => {
    try {
      const newRoom = await apiService.createChatRoom(roomData)
      chatRooms.value.unshift(newRoom)
      
      // 自动加入新创建的聊天室
      await signalRService.joinChatRoom(newRoom.id)
      
      return newRoom
    } catch (err: any) {
      error.value = err.response?.data?.message || '创建聊天室失败'
      throw err
    }
  }

  // 创建直接聊天
  const createDirectChat = async (targetUserId: number) => {
    try {
      const chatRoom = await apiService.createDirectChat({ targetUserId })
      
      // 检查是否已存在，避免重复添加
      const existingRoom = chatRooms.value.find(room => room.id === chatRoom.id)
      if (!existingRoom) {
        chatRooms.value.unshift(chatRoom)
      }
      
      await signalRService.joinChatRoom(chatRoom.id)
      return chatRoom
    } catch (err: any) {
      error.value = err.response?.data?.message || '创建直接聊天失败'
      throw err
    }
  }

  // 选择聊天室
  const selectChatRoom = async (chatRoom: ChatRoom) => {
    try {
      // 检查 SignalR 连接状态
      if (!signalRService.isConnected) {
        throw new Error('SignalR连接未建立，无法选择聊天室')
      }

      currentChatRoom.value = chatRoom

      // 加入聊天室
      await signalRService.joinChatRoom(chatRoom.id)

      // 获取聊天记录
      await fetchChatHistory(chatRoom.id)

      // 标记为已读
      await markAsRead(chatRoom.id)
    } catch (err: any) {
      error.value = err.message || '选择聊天室失败'
      console.error('选择聊天室失败:', err)
      throw err
    }
  }

  // 获取聊天记录
  const fetchChatHistory = async (chatRoomId: number, pageNumber: number = 1) => {
    try {
      const history = await apiService.getChatHistory(chatRoomId, pageNumber, 50)
      
      if (pageNumber === 1) {
        // 第一页，替换现有消息
        messages.value = messages.value.filter(msg => msg.chatRoomId !== chatRoomId)
        messages.value.push(...history.messages)
      } else {
        // 后续页，追加到开头
        const existingMessages = messages.value.filter(msg => msg.chatRoomId === chatRoomId)
        const newMessages = history.messages.filter(
          newMsg => !existingMessages.some(existing => existing.id === newMsg.id)
        )
        messages.value = [...newMessages, ...messages.value]
      }
      
      return history
    } catch (err: any) {
      error.value = err.response?.data?.message || '获取聊天记录失败'
      throw err
    }
  }

  // 发送消息
  const sendMessage = async (messageData: SendMessageRequest) => {
    try {
      // 检查 SignalR 连接状态
      if (!signalRService.isConnected) {
        throw new Error('SignalR连接未建立，无法发送消息')
      }

      // 通过 SignalR 发送消息
      await signalRService.sendMessage(messageData)
    } catch (err: any) {
      error.value = err.message || err.response?.data?.message || '发送消息失败'
      console.error('发送消息失败:', err)
      throw err
    }
  }

  // 标记为已读
  const markAsRead = async (chatRoomId: number) => {
    try {
      await signalRService.markAsRead(chatRoomId)

      // 更新本地聊天室的未读计数
      const room = chatRooms.value.find(r => r.id === chatRoomId)
      if (room) {
        room.unreadCount = 0
        console.log(`聊天室 ${chatRoomId} 已标记为已读，未读计数重置为 0`)
      }
    } catch (err: any) {
      console.error('标记已读失败:', err)
    }
  }

  // 开始输入
  const startTyping = async (chatRoomId: number) => {
    try {
      await signalRService.startTyping(chatRoomId)
    } catch (err) {
      console.error('发送输入状态失败:', err)
    }
  }

  // 停止输入
  const stopTyping = async (chatRoomId: number) => {
    try {
      await signalRService.stopTyping(chatRoomId)
    } catch (err) {
      console.error('发送停止输入状态失败:', err)
    }
  }

  // 删除消息
  const deleteMessage = async (messageId: number) => {
    try {
      await signalRService.deleteMessage(messageId)
    } catch (err: any) {
      error.value = err.response?.data?.message || '删除消息失败'
      throw err
    }
  }

  // 编辑消息
  const editMessage = async (messageId: number, newContent: string) => {
    try {
      await signalRService.editMessage(messageId, newContent)
    } catch (err: any) {
      error.value = err.response?.data?.message || '编辑消息失败'
      throw err
    }
  }

  // 辅助方法
  const addMessage = (message: Message) => {
    const existingIndex = messages.value.findIndex(msg => msg.id === message.id)
    if (existingIndex === -1) {
      messages.value.push(message)
    }
  }

  const updateMessage = (updatedMessage: Message) => {
    const index = messages.value.findIndex(msg => msg.id === updatedMessage.id)
    if (index !== -1) {
      messages.value[index] = updatedMessage
    }
  }

  const removeMessage = (messageId: number) => {
    const index = messages.value.findIndex(msg => msg.id === messageId)
    if (index !== -1) {
      messages.value.splice(index, 1)
    }
  }

  const updateChatRoomLastMessage = (message: Message) => {
    const room = chatRooms.value.find(r => r.id === message.chatRoomId)
    if (room) {
      room.lastMessage = message
      // 如果不是当前聊天室，增加未读计数
      if (currentChatRoom.value?.id !== message.chatRoomId) {
        room.unreadCount = (room.unreadCount || 0) + 1
      }
    }
  }

  const updateUserOnlineStatus = (userId: number, isOnline: boolean) => {
    // 更新聊天室成员的在线状态
    chatRooms.value.forEach(room => {
      const member = room.members.find(m => m.id === userId)
      if (member) {
        member.isOnline = isOnline
      }
    })
    
    // 更新消息发送者的在线状态
    messages.value.forEach(message => {
      if (message.sender?.id === userId) {
        message.sender.isOnline = isOnline
      }
    })
  }

  const addTypingUser = (chatRoomId: number, userId: number) => {
    if (!typingUsers.value.has(chatRoomId)) {
      typingUsers.value.set(chatRoomId, new Set())
    }
    typingUsers.value.get(chatRoomId)!.add(userId)
  }

  const removeTypingUser = (chatRoomId: number, userId: number) => {
    const typingSet = typingUsers.value.get(chatRoomId)
    if (typingSet) {
      typingSet.delete(userId)
      if (typingSet.size === 0) {
        typingUsers.value.delete(chatRoomId)
      }
    }
  }

  // 清除错误
  const clearError = () => {
    error.value = null
  }

  // 清除所有数据
  const clearAll = () => {
    chatRooms.value = []
    currentChatRoom.value = null
    messages.value = []
    typingUsers.value.clear()
    onlineUsers.value.clear()
    error.value = null
  }

  return {
    // 状态
    chatRooms,
    currentChatRoom,
    messages,
    typingUsers,
    onlineUsers,
    isLoading,
    error,
    
    // 计算属性
    sortedChatRooms,
    currentChatMessages,
    currentTypingUsers,
    
    // 方法
    initializeSignalRListeners,
    fetchChatRooms,
    createChatRoom,
    createDirectChat,
    selectChatRoom,
    fetchChatHistory,
    sendMessage,
    markAsRead,
    startTyping,
    stopTyping,
    deleteMessage,
    editMessage,
    clearError,
    clearAll
  }
})
